package com.withmiku.world.user.repository;

import com.withmiku.world.user.entity.Post;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

// 优化：未来如果用户数据量太大，可替换为Cursor分页（无限下拉）策略
public interface PostRepository extends JpaRepository<Post, Long> {
    // 按照创建时间倒序分页查询（动态主页，所有人可见）
    Page<Post> findAllByOrderByCreateTimeDesc(Pageable pageable);

    // 查询某个用户的所有动态
    Page<Post> findByUserIdOrderByCreateTimeDesc(Long userId, Pageable pageable);

    @Modifying(clearAutomatically = true)
    @Transactional  // 注意：自定义UPDATE/DELETE必须加这个才能让jpa自动提交
    @Query("UPDATE Post p SET p.likeCount = p.likeCount + 1 WHERE p.id = :postId")
    void incrementLikeCount(@Param("postId") Long postId);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query("UPDATE Post p SET p.likeCount = p.likeCount - 1 WHERE p.id = :postId AND p.likeCount > 0")
    void decrementLikeCount(@Param("postId") Long postId);

    @Query("SELECT p.likeCount FROM Post p WHERE p.id = :postId")
    Long findLikeCountById(@Param("postId") Long postId);
}
